import React from 'react'
import {Row, Col, Button, Table, Input, Tag, Avatar, Modal, message,Badge} from 'antd'

import '../styles.css'
import Model from "./Model"
import axios from "axios";
import api from "../../../api/api";
import Addcompany from "../../Organization/CompanyManagement";
import Model2 from "./Model2";

const {Search} = Input;
const statusMap = ['default', 'success'];
const status = ['不可用', '可用'];

class Roles extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            pageNum:1,
            pageSize:10,
            data: [],
            total:"",
            modelData:{
                width:700,
                title: "新增角色",
                gridList: {},
                visible: false,
                type: 1,//:1,添加 2,编辑
            },
            modelData2:{
                title: "分配资源",
                resource: {},
                visible: false,
            }
        };
    }

    componentDidMount() {
        this.getRoleSettings();
    }


    columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            className: "elementHidden",
            key: 'id',
            width: '20%'
        },
        {
            title: '角色名称',
            dataIndex: 'roleName',
            key: 'roleName',
            width: '20%'
        },
        {
            title: '角色代码',
            dataIndex: 'roleCode',
            key: 'roleCode',
            width: '20%'
        },
        {
            title: '状态',
            dataIndex: 'status',
            width: '20%',
            key: 'status',
            filters: [
                {
                    text: status[0],
                    value: 0,
                },
                {
                    text: status[1],
                    value: 1,
                }
            ],
            onFilter: (value, record) => record.status.toString() === value,
            render(val) {
                return <Badge status={statusMap[val]} text={status[val]} />;
            },

        },
        {
            title: '操作',
            dataIndex: 'option',
            width: '40%',
            key: 'option',
            render: (text, record, index) => {
                return (
                    <span>
            <a className="optionMargin" onClick={() => this.onClickEdit(record)}>编辑</a>
            <a className="optionMargin" onClick={() => this.onClickDelete(record)}>删除</a>
            <a className="optionMargin" onClick={() => this.onClickSource(record)}>资源分配</a>
          </span>
                )
            }
        }
    ];

    getRoleSettings() {
        let that = this;
        axios.post(api.api_URL + "/admin/role/queryRoles?pageNum=" + this.state.pageNum + "&pageSize=" + this.state.pageSize, {
        }, {
            headers: {
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            console.log(res.data)
            let totalSize = res.data.object.totalSize;
            const dataList = [];
            for (let i = 0; i < res.data.object.records.length; i++) {
                let resContent = res.data.object.records[i];
                const content = {};
                content.key = (i + 1);
                content.id = resContent.id;
                content.roleName = resContent.roleName;
                content.roleCode = resContent.roleCode;
                content.status = resContent.status;
                dataList[i] = content;
            }
            that.setState({
                data: dataList,
                total: totalSize
            })
        }).catch(function (err) {
            message.error({content:"加载失败，请重新尝试！"})
            console.log(err);
        });
    }

//分页
    onBaseClick(current, pageSize) {
        this.setState({
            pageNum: current,
            pageSize: pageSize
        }, () => {
            this.getRoleSettings()
        });

    }

    onclickAdd() {
        console.info("新增角色");
        this.setState({
            modelData:{
                width:700,
                title: "新增角色",
                type:1,
                visible: true
            }
        })
    }

    //编辑
    onClickEdit(item) {
        console.info("编辑");
        this.setState({
            modelData:{
                width:700,
                title: "编辑角色",
                visible: true,
                type:2,
                gridList:item
            }
        },()=>{
            this.child.initEditData();
        });

    }

    //删除
    onClickDelete(item) {
        let that = this;
        let configModel = Modal.confirm({
            title: '删除',
            content: '是否确认删除？',
            onOk: (values) => {
                return new Promise((res, rej) => {
                    let url = api.api_URL + "/admin/role/deleteRole?id="+item.id;
                    axios.get(url, {
                        headers: {
                            "Content-Type": api.ContentType
                        }
                    }).then(function (res) {
                        if (res.data.errorCode != 1) {
                            message.error({content:"删除失败，请重新尝试！"})
                            return;
                        }
                        message.success({content:"删除成功！"})
                        that.setState({
                            data: []
                        })
                        that.getRoleSettings();
                        configModel.destroy();
                    }).catch(function (err) {
                        message.error({content:"删除失败，请重新尝试！"})
                        console.log(err);
                    })
                }).catch((e) => console.warn(e));

            },
            onCancel() {
            },
        })
    }

    //分配资源
    onClickSource(item){
        console.info("分配资源");
        console.info(item);
        this.setState({
            modelData2:{
                title: "分配资源",
                visible: true,
                resource:item
            }
        });
    }
    onRef =(ref) => {
        this.child = ref
    }

    onRef2=(name,ref) => {
        switch (name) {
            case 'Model2':
                this.child = ref
                break
        }
    }


    handleCancel = e => {
        console.log(e);
        this.setState({
            modelData:{
                visible: false,
            }
        });
        this.getRoleSettings();
    };

    handleCancel2 = e => {
        console.log(e);
        this.setState({
            modelData2:{
                visible: false,
            }
        });
        this.getRoleSettings();
    };

    render() {

        return (
            <div className="girdBg">
                <Row className="searchBox">
                    <Col span={20}>
                    </Col>
                    <Col span={4} className="btnRight">
                        <Button icon={"save"} type='primary' style={{marginLeft: 30}}
                                onClick={this.onclickAdd.bind(this)}>新增角色</Button>
                    </Col>
                </Row>
                <Row style={{margin: 30}}>
                    <Table
                        columns={this.columns}
                        dataSource={this.state.data}
                        scroll={{x: 'max-content'}} // 加上这条  横向滚动  支持此属性的浏览器内容就不会换行了
                        columns={this.columns.map(item => { // 通过配置 给每个单元格添加不换行属性
                            const fun = () => ({style: {whiteSpace: 'nowrap'}});
                            item.onHeaderCell = fun;
                            item.onCell = fun;
                            return item;
                        })}
                        pagination={{
                            simple: false,
                            current: this.state.pageNum,
                            total: this.state.total,
                            pageSize: this.state.pageSize,
                            showTotal: (count = this.state.total) => {
                                return '共' + count + '条'
                            },
                            onChange: (current, pageSize) => {
                                this.onBaseClick(current, pageSize)
                            }
                        }}
                    />
                </Row>
                <Model data={this.state.modelData} handleCancel={this.handleCancel} refresh={this.refresh}
                       onRef={this.onRef} visible={this.state.modelData.visible} history={this.props.history} />
                <Model2 data={this.state.modelData2} handleCancel={this.handleCancel2}
                       onRef={this.onRef2} visible={this.state.modelData2.visible} history2={this.props.history} />
            </div>
        )
    }
}

export default Roles
